package com.omo.infrastructure.excel;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.aspose.cells.Cell;
import com.aspose.cells.Cells;
import com.aspose.cells.Worksheet;
import com.omo.types.constant.ExcelConstant;
import com.omo.types.excel.BaseExportExcelData;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Service
public class ExcelExport extends AbstractExcelExport {
    @Override
    protected void refactorTemplate(Worksheet worksheet, Integer expandBeginIndex, Integer expandBeginIndexAscii,
                                    Integer expandParams, Collection<?> expandParamsCollection) {
        // 常量定义
        final int TITLE_ROW_INDEX = 0;
        final int CHILDREN_TITLE_ROW_INDEX = 1;
        final int BODY_ROW_INDEX = 2;

        Cells cells = worksheet.getCells();
        int templateMaxRow = cells.getMaxRow();
        Map<Integer, Cell> childrenTitleMap = new HashMap<>();

        // 收集子标题信息
        if (templateMaxRow != 1 && expandParams > 0) {
            for (int i = 0; i < expandParams; i++) {
                Cell cell = cells.get(CHILDREN_TITLE_ROW_INDEX, expandBeginIndex + i);
                childrenTitleMap.put(i, cell);
            }
        }

        // 计算需要插入的列数并执行插入
        int expandCount = expandParamsCollection.size() - 1;
        int totalExpandNum = expandParams * expandCount;
        if (totalExpandNum > 0) {
            cells.insertColumns(expandBeginIndex + expandParams, totalExpandNum);
        }

        int currentColumn = expandBeginIndex + expandParams;
        int flag = expandParams;

        // 根据模板最大行数处理不同情况
        if (templateMaxRow > 1) {
            processTemplateWithMultipleRows(cells, currentColumn, totalExpandNum, flag, expandBeginIndexAscii,
                    expandParams, childrenTitleMap);
        } else if (templateMaxRow == 1) {
            processTemplateWithSingleRow(cells, currentColumn, totalExpandNum, flag, expandBeginIndexAscii,
                    expandParams);
        }
    }

    /**
     * 处理多行模板
     */
    private void processTemplateWithMultipleRows(Cells cells, int startColumn, int totalColumns, int initialFlag,
                                                 int asciiStart, int expandParams, Map<Integer, Cell> childrenTitleMap) {
        int flag = initialFlag;
        for (int i = startColumn; i < startColumn + totalColumns; i++) {
            int offset = i - expandParams;
            char columnChar = (char) (asciiStart + offset);

            // 设置标题行
            if (flag == expandParams) {
                cells.get(0, i).setValue(ExcelConstant.EXCEL_TITLE_PREFIX + columnChar + ExcelConstant.EXCEL_CELL_SUFFIX);
                flag = 0;
            }

            // 设置子标题行
            if (!childrenTitleMap.isEmpty()) {
                Cell titleCell = childrenTitleMap.get(flag);
                if (titleCell != null) {
                    cells.get(1, i).setValue(titleCell.getValue());
                }
            }

            // 设置内容行
            cells.get(2, i).setValue(ExcelConstant.EXCEL_BODY_PREFIX + columnChar + ExcelConstant.EXCEL_CELL_SUFFIX);
            flag++;
        }
    }

    /**
     * 处理单行模板
     */
    private void processTemplateWithSingleRow(Cells cells, int startColumn, int totalColumns, int initialFlag,
                                              int asciiStart, int expandParams) {
        int flag = initialFlag;
        for (int i = startColumn; i < startColumn + totalColumns; i++) {
            int offset = i - expandParams;
            char columnChar = (char) (asciiStart + offset);

            // 设置标题行
            if (flag == expandParams) {
                cells.get(0, i).setValue(ExcelConstant.EXCEL_TITLE_PREFIX + columnChar + ExcelConstant.EXCEL_CELL_SUFFIX);
                flag = 0;
            }

            // 设置内容行
            cells.get(1, i).setValue(ExcelConstant.EXCEL_BODY_PREFIX + columnChar + ExcelConstant.EXCEL_CELL_SUFFIX);
            flag++;
        }
    }

    @Override
    protected void writeDataToExcel(File outPutFile, BaseExportExcelData data, byte[] newExcelTemplateBytes) {
        try (InputStream templateInputStream = new ByteArrayInputStream(newExcelTemplateBytes)) {
            // 1.1、创建工作表 Excel
            ExcelWriter excelWriter = EasyExcel.write(outPutFile)
                    .withTemplate(templateInputStream)
                    .build();

            // 1.2、创建工作表 sheet
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            // 1.3、设置填充配置，允许多行填充
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();

            // 2. 填充头部数据
            excelWriter.fill(data.getTitle(), writeSheet);

            // 4. 填充标体
            FillWrapper bodyFillWrapper = new FillWrapper("body", data.getBody());
            excelWriter.fill(bodyFillWrapper, fillConfig, writeSheet);

            excelWriter.finish();

        }catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
